

const workercode = () => {


  var formatTreeData = (treeData, parentKey) => {
    const result = [];
    let flattenObj = {};
    for (let i = 0; i < treeData.length; i++) {
      let formattedPersons = [];
      let children = [];
      const personFlattenObj = {};
      let childFlattenObj = {};

      if (treeData[i].persons) {
        formattedPersons = treeData[i].persons.map((el) => {
          const obj = {
            key: el.userId,
            title: el.name,
            type: el.type,
            icon: el.icon,
            parentKey: treeData[i].id
          };
          personFlattenObj[obj.key] = obj;
          return obj;
        });
      }

      if (treeData[i].children) {
        const tmp = formatTreeData(treeData[i].children || [], treeData[i].id);
        children = tmp.result;
        childFlattenObj = tmp.flattenObj;
        if (formattedPersons) {
          children = children
            ? children.concat(formattedPersons)
            : formattedPersons;

          childFlattenObj = Object.assign(
            {},
            childFlattenObj,
            personFlattenObj
          );
        }
      }

      var orgObj = {};
      orgObj[treeData[i].id] = {
        key: treeData[i].id,
        title: treeData[i].orgName,
        type: treeData[i].type,
        parentKey,
        icon: treeData[i].icon,
        children: children
      };

      flattenObj = Object.assign({}, orgObj, flattenObj, childFlattenObj);

      result.push({
        key: treeData[i].id,
        title: treeData[i].orgName,
        type: treeData[i].type,
        children: children,
        icon: treeData[i].icon,
        parentKey: parentKey
      });
    }
    return { result, flattenObj };
  };

  self.onmessage = (event) => {

    let orgData = event.data;
    if (!orgData) return;
    orgData = orgData instanceof Array ? orgData : [orgData];
    orgData = formatTreeData(orgData);
    self.postMessage(orgData);
  };

};

// 把脚本代码转为string
let code = workercode.toString();
code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));

const blob = new Blob([code], { type: 'application/javascript' });
const worker_script = URL.createObjectURL(blob);

// console.log('worker_script:', worker_script);
export default worker_script;